﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tecnicas.CasoEstudio.Back.Dominio;
using Tecnicas.CasoEstudio.Repositorio;
using System.Collections;


namespace Tecnicas.CasoEstudio.Back.Persistencia
{
    public class PeliculaDataMapper : AbstractDataMapper
    {
        public PeliculaDataMapper()
        {             
        }
        

        public override object Insert(DomainObject obj)
        {
            if (typeof(Pelicula) != obj.GetType())
                throw new ApplicationException("Este mapper solo opera con objetos del tipo Pelicula");

            if (obj.PersistenceId == null)
            {
                obj.PersistenceId = RepositorioVersionado.Instance.GetNextKey();
                obj.PersistenceVersion = 0;
            }

            Pelicula pelicula = (Pelicula)obj;
            Pelicula peliculaCopia = this.ClonePlainObject(pelicula);

            RepositorioVersionado.Instance.Guardar(peliculaCopia, peliculaCopia.PersistenceId, peliculaCopia.PersistenceVersion, ++peliculaCopia.PersistenceVersion);

            pelicula.PersistenceVersion++;
            return pelicula;
        }
        private Pelicula ClonePlainObject(Pelicula pelicula)
        {
            Pelicula peliculaCopia = new Pelicula(pelicula.Titulo, pelicula.CodigoPrecio);
            peliculaCopia.PersistenceId = pelicula.PersistenceId;
            peliculaCopia.PersistenceVersion = pelicula.PersistenceVersion;

            return peliculaCopia;
        }
        public override void Delete(long? id, object version)
        {
            RepositorioVersionado.Instance.Eliminar(typeof(Pelicula), id, version);
        }
        public override void Delete(DomainObject obj)
        {
            this.Delete(obj.PersistenceId, obj.PersistenceVersion);
        }

        public override DomainObject Find(long? id)
        {
            return (Pelicula)RepositorioVersionado.Instance.ObtenerPorId(typeof(Pelicula), id);
        }

        public override ArrayList FindAll()
        {
            return RepositorioVersionado.Instance.ObtenerPorTipo(typeof(Pelicula));
        }

    }
}
